package leetCode;

import java.util.*;

public class t350d2 {
    public static void main(String[] args) {
        new Solutiont350d2().intersection(new int[]{1,2,2,1},new int[]{2,2});
    }
}
class Solutiont350d2 {
    public int[] intersection(int[] nums1, int[] nums2) {
       List<Integer> list=new ArrayList<>();
       Arrays.sort(nums1);
       Arrays.sort(nums2);
       int s1Index=0;
       int s2Index=0;
       while (s1Index<nums1.length&&s2Index<nums2.length){
           if (nums1[s1Index]==nums2[s2Index]){
               list.add(nums1[s1Index]);
               s2Index++;
               s1Index++;
           }else if (nums1[s1Index]>nums2[s2Index]){
               s2Index++;
           }else {
               s1Index++;
           }
       }
       return list.stream().mapToInt(x->x).toArray();
    }
}
